package com.seu.multithread.demo02;

/**
 * @author liangfeihu
 * @since 2019/2/18
 */
public class Test2 {
    private static int state = 1;

    public static void main(String[] args) {
        final Test2 t = new Test2();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (t) {
                        if (state != 1) {
                            try {
                                t.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            System.out.println("轮到线程一开始执行");
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //线程1执行一秒
                        state = 2;
                        t.notifyAll();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (t) {
                        if (state != 2) {
                            try {
                                t.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            System.out.println("轮到线程二开始执行");
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //线程1执行一秒
                        state = 1;
                        t.notifyAll();
                    }
                }
            }
        }).start();
    }

}
